(function() {
  angular
    .module('api-service', [])
    .service('tradeApi', function($http, $q, $location, alertTip, centerdilog) {
      var self = this;
      this.mobile = '';
      this.sessionId = '';
      this.query = function(data) {
        data.data.sessionId = self.sessionId;
        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: './api/' + data.funcId,
            data: data.data || {}
          })
          .then(function(res) {
            if (res.data.code !== '0000') {
              var err = new Error(res.data.msg);
              err.code = res.data.code;
              throw err;
            }
            deferred.resolve(res.data.result);
          })
          .catch(function(err) {
            if (err.code === '1006') {
              self.sessionId = '';
              sessionStorage.removeItem('session');
              sessionStorage.removeItem('mobile');

              alertTip.open({
                msg: '登录过期，请重新登陆',
              });
            } else {
              centerdilog
                .open({
                  oktxt: '关闭',
                  msg: err.message,
                  cancel_hiden: true,
                });
            }
            deferred.reject(err);
          });
        return deferred.promise;
      };

      this.opt = {
        url: './eamapi',
        onStart: function() {},
        onEnd: function() {},
        timeout: 5000,
      };

      etApi.default(self.opt);

      this.etQuery = function(data) {
        var deferred = $q.defer();
        data.session = sessionStorage.getItem('eam_session');
        etApi
          .query({
            data: data
          })
          .then(function(res) {
            deferred.resolve(res.result);
          })
          .catch(function(err) {
            centerdilog
              .open({
                oktxt: '关闭',
                msg: err,
                cancel_hiden: true,
              });
            deferred.reject(err);
          });
        return deferred.promise;
      };
    });

})(angular, etApi);